<template>
  <div class="app-container">
    <!--用户数据-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['enterprise:user:add']">新增</el-button>
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="50" align="center" /> -->
      <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
      <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
      <el-table-column label="所在部门" align="center" key="deptName" prop="deptName" :show-overflow-tooltip="true" />
      <el-table-column label="角色" align="center" key="roleName" prop="roleName" width="140">
        <template slot-scope="scope">
          <div class="roleContainer">
            <span class="roleName">{{ scope.row.roleName }}</span>
            <el-popover
              placement="top"
              title=""
              width="200"
              trigger="click"
              :ref="'popover-userRole-'+scope.$index"
            >
              <div>{{ scope.row.roleNames }}</div>
              <el-button type="text" slot="reference" @click="showUserRole(scope.$index, scope.row)">更多</el-button>
            </el-popover>
          </div>

        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" align="center" key="status" v-if="columns[5].visible">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.status == 0 ? '启用' : '禁用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="160">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.userId !== 1">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['enterprise:user:edit']">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handlePassword(scope.row)"
            v-hasPermi="['enterprise:user:remove']">修改密码</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['enterprise:user:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <edit v-model="open" :title="title" :data="form" @success="getList" />
    <password v-model="passwordVisible" :userId="userId" />
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import edit from './edit.vue'
import password from "./password.vue";
import { listUserBusiness, getUserBusiness, delUserBusiness, getUserRolesByUserId } from '@/api/enterprise/user'

export default {
  name: "User",
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { Treeselect, edit, password },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //显示 修改密码
      passwordVisible: false,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      //用户id
      userId: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
    };
  },
  computed:{
    getRoleNames:{
      get(){
        return (rolesList)=>{
          if(!rolesList){
            return ''
          }
          console.log('getRoleNames',rolesList)
          return rolesList.map(item => item.roleName).join(',')
        }
      }
    }
  },

  watch: {
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUserBusiness(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    // 用户状态修改
    // handleStatusChange(row) {
    //   let text = row.status === "0" ? "启用" : "停用";
    //   this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function () {
    //     return changeUserStatus(row.userId, row.status);
    //   }).then(() => {
    //     this.$modal.msgSuccess(text + "成功");
    //   }).catch(function () {
    //     row.status = row.status === "0" ? "1" : "0";
    //   });
    // },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userName: '',
        phonenumber: undefined,
        roleId: undefined,
        status: '0',
        depId: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      // this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增账号";

    },
    //编辑
    handleUpdate(row) {
      getUserBusiness(row.userId).then(response => {
        this.form = response.data
        this.form.depId = row.depId
        this.title = '编辑账号'
        this.open = true;
      })

    },
    //修改密码
    handlePassword(row) {
      this.userId = row.userId
      this.passwordVisible = true
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      // let data = {
      //   depId: row.depId,
      //   userId: row.userId
      // }
      this.$modal.confirm('确定删除数据？').then(function () {
        return delUserBusiness(userIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    showUserRole(index, row) {
      console.log(index)
      if(this.$refs['popover-userRole-' + index].showPopper === true){
        this.$refs['popover-userRole-' + index].showPopper = false
        return
      }
      getUserRolesByUserId(row.userId).then(response => {
        console.log('getUserRolesByUserId',response.data)
        let roles = response.data
        this.$set(row, 'roleNames', roles.map(item => item.roleName).join(' '))
        this.$nextTick(() => {
          for (let i = 0; i < this.userList.length; i++) {
            if (i !== index) {
              this.$refs['popover-userRole-' + i].showPopper = false
            }
          }
          this.$refs['popover-userRole-' + index].showPopper = true
          this.$forceUpdate()
        })
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.roleContainer{
  display: flex;
  align-items: baseline;
  .roleName{
    margin-right: 5px;
  }
}
</style>
